/*
 * Calculator.cpp
 *
 *  Created on: 2010-04-08
 *      Author: mateusz
 */

#include "Calculator.h"

#include <math.h>
#include <string.h>

#include "BadInputException.h"

extern BadInputException badInputException;

int Calculator::sign = 1;

//------------------------------------------------------------------------------

int Calculator::getPrioritaire(char c)
{
	if( c == '^' ) {
		return 3;
	} else if( c == '*' || c == '/' || c == ' ' || c == '(' || (c >= 65 && c <= 122 )) {
		return 2;
	} else if( c == '+' || c == '-' ) {
		return 1;
	} else {
		return 0;
	}
}

//------------------------------------------------------------------------------

double Calculator::calculate( double a, double b, char operation ) {
	if( operation == '^' ) {
		return pow(a,b);
	} else if( operation == '*' ) {
		return a*b;
	} else if( operation == '/' ) {
		return a/b;
	} else if( operation == '+' ) {
		return a+sign*b;
	} else if( operation == '-' ) {
		return a-sign*b;
	} else if( operation == '('  || (operation >= 65 && operation <= 122 )) {
		return a*b;
	}

	throw badInputException;
}

//------------------------------------------------------------------------------

double Calculator::calculate( const char* f, double v ) {
	if( strcmp(f,"sin") == 0 ) {
		return sin( v );
	} else if( strcmp(f,"cos") == 0 ) {
		return cos( v );
	} else if( strcmp(f,"tg") == 0 ) {
		return tan( v );
	} else if( strcmp(f,"ctg") == 0 ) {
		return 1/tan(v);
	} else if( strcmp(f,"sqrt") == 0 ) {
		return sqrt(v);
	} else if( strcmp(f,"e") == 0 ) {
		return exp( v );
	} else if( strcmp(f,"abs") == 0 ) {
		return fabs( v );
	} else if( strcmp(f,"arcsin") == 0 ) {
		return asin( v );
	} else if( strcmp(f,"arccos") == 0 ) {
		return acos( v );
	} else if( strcmp(f,"arctg") == 0 ) {
		return atan( v );
	} else if( strcmp(f,"arcctg") == 0 ) {
		return 1/atan( v );
	} else if( strcmp(f,"ln") == 0) {
		if( v <= 0 )
			return 0.0;
		return log( v );
	}

	throw badInputException;
}

//------------------------------------------------------------------------------
